from django.views import View
from django_filters.rest_framework import DjangoFilterBackend
from redis import RedisError
from rest_framework import status
from rest_framework import viewsets,filters
from rest_framework.decorators import action
from rest_framework.views import APIView

from .serializes import *
from .models import BookInfo, HeroInfo
from rest_framework.response import Response

# class BookInfoView(APIView):
#     def get(self, request):
#         books = BookInfo.book.all()
#         serializer = BookInfoModelSerializer(instance=books, many=True)
#         return Response(serializer.data, status=status.HTTP_200_OK)
#
#     def post(self, request):
#         dict_data = request.data
#         serializer = BookInfoModelSerializer(data=dict_data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data, status=status.HTTP_201_CREATED)


# class BookInfoDetailView(APIView):
#     def get(self, request, pk):
#         book = BookInfo.book.get(pk=pk)
#         serializer = BookInfoModelSerializer(instance=book)
#         return Response(serializer.data,status=status.HTTP_200_OK)
#
#     def put(self, request, pk):
#         dict_data = request.data
#         book = BookInfo.book.get(pk=pk)
#         serializer = BookInfoModelSerializer(instance=book,data=dict_data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(serializer.data, status=status.HTTP_201_CREATED)
#
#     def delete(self, request, pk):
#         book = BookInfo.book.get(pk=pk)
#         book.delete()
#         return Response(status=status.HTTP_204_NO_CONTENT)

class BookModelViewSet(viewsets.ModelViewSet):
    serializer_class = BookInfoModelSerializer
    queryset = BookInfo.book.all()
    # 过滤
    filter_backends = (DjangoFilterBackend,filters.OrderingFilter)
    filterset_fields = ('id', 'btitle')
    # 排序
    # filter_backends = (filters.OrderingFilter,)  # 格式: ordering=字段
    ordering_fields = ('id', 'bread', "bcomment", "bpub_date")

    @action(methods=['GET'], detail=False)
    def special_books(self, request):  # 生成的路径规则: 前缀/方法名/
        # 查询包含金瓶的书籍
        books = BookInfo.objects.filter(btitle__contains="金瓶")
        serializer = self.get_serializer(instance=books, many=True)

        # 异常测试
        # 1,抛出API异常
        # raise APIException('api异常了')

        # 2,抛出数据库异常
        # raise DatabaseError('数据库,大出血')
        raise RedisError('hahah')
        return Response(serializer.data)

    @action(methods=["PUT"], detail=True)
    def update_book_bread(self, request, pk):  # 生成规则: 前缀/{pk}/方法名/
        # 更新指定书籍的阅读量
        dict_data = request.data
        book = self.get_object()

        # 获取序列化器,校验,入库,partial=True可以更新局部
        serializer = self.get_serializer(instance=book, data=dict_data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)